package com.efounder.email.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.email.adapter.DetailListAdapter;
import com.efounder.email.dao.AttachmentsDAO;
import com.efounder.email.dao.InboxEmailsDAO;
import com.efounder.email.dao.OutboxEmailsDAO;
import com.efounder.email.model.AttachFile;
import com.efounder.email.model.Email;
import com.efounder.email.util.AbStrUtil;
import com.efounder.email.util.FileUtil;
import com.efounder.frame.utils.Constants;
import com.efounder.ospmobilelib.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 邮件详情
 *
 * @author yqs
 *
 */
public class EmailDetailsAct extends Activity implements OnClickListener {
	final static String TAG = "EmailDetailsAct";
	private ImageView backImageView;
	private TextView hideTextView, detailTextView;// 详情 隐藏
	// 邮件主题，发件人，发件人邮箱，发件人1，收件人，收件人邮箱，邮件时间,抄送人名字，密送人名字
	private TextView emailthemeText, emailAdresserText, adresserEmailText,
			emailAdresserText1, emailAdresserAdressText, emaishoujianrenName,
			emailshoujianrenText, emailTimeText, chaosongrtenTextView,
			misongrenTextView;
	private TextView emailContentTextView;// 邮件内容
	private RelativeLayout hideRelativeLayout, simplerRelativeLayout;
	private ListView listView;
	private Email emailData;
	private Email contentEmail;
	private Email dbEmail;
	private WebView webView;
	private String emailType;

	// 回复，转发删除按钮
	private LinearLayout replyLayout, copytoLayout, deleteLayout;
	private ListView attachListView;
	private DetailListAdapter listAdapter;
	private ArrayList<AttachFile> files;
	private String boxType;// 判断是收件箱还是发件箱传过来的数据
	InboxEmailsDAO inboxEmailsDAO = new InboxEmailsDAO(this);
	OutboxEmailsDAO outboxEmailsDAO = new OutboxEmailsDAO(this);
	AttachmentsDAO attachmentEmailsDAO = new AttachmentsDAO(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.email_detailcontent);
		// 初始化view
		initView();

		emailType = (String) getIntent().getSerializableExtra("emailtype");

		contentEmail = new Email();
		contentEmail.setFrom(null);
		// 从intent中得到传递的数据
		emailData = new Email();
		emailData = (Email) getIntent().getSerializableExtra("emailmap");
		// 判断是收件箱还是发件箱传过来的数据
		 boxType = (String) getIntent().getSerializableExtra("box");
		//请求邮件详情数据
		 //判断是从收件箱还是发件箱 跳转过来的，以此决定从收件箱还是发件箱数据库中查询数据  ，如果没有数据，则从服务器中加载
		if ( boxType.equals("inbox")) {
			Email email = inboxEmailsDAO.queryEmailById(emailData
					.getMessageID());
			if (email != null) {
				dbEmail = email;
				String receiver = email.getTo();
				if (receiver != null && !receiver.equals("")) {
					files = attachmentEmailsDAO.queryFiles(emailData.getMessageID());
					initData(email);
				} else {
					loadHeadOfficeDetailByNet();
				}
			}else {
				loadHeadOfficeDetailByNet();
			}
		}

		else if (boxType.equals("outbox")) {
			Email email = outboxEmailsDAO.queryEmailById(emailData
					.getMessageID());
			if (email != null) {
				dbEmail = email;
				String sender = email.getFrom();
				if (sender != null && !sender.equals("")) {
					files = attachmentEmailsDAO.queryFiles(emailData.getMessageID());
					initData(email);
				} else {
					loadHeadOfficeDetailByNet();
				}
			}else {
				loadHeadOfficeDetailByNet();
			}
		}

		// 初始化数据
		// initData();

	}





	@SuppressWarnings("unchecked")
	private void initData(Email contentEmail) {

		emailthemeText.setText(emailData.getSubject());// 邮件主题
		emailAdresserText.setText(contentEmail.getFrom());// 发件人
		emailAdresserText1.setText(contentEmail.getFrom());
		emailTimeText.setText(emailData.getSentdata());// 发送时间
		emailAdresserAdressText.setText(emailData.getFromAddress());// 发件人邮箱
		emaishoujianrenName.setText(AbStrUtil.getEmailAddress(contentEmail
				.getTo()));// 收件人姓名
		emailshoujianrenText.setText(contentEmail.getTo());// 收件人邮箱

		chaosongrtenTextView.setText(contentEmail.getCopyTo());// 抄送人

		misongrenTextView.setText(contentEmail.getSecretTo());// 密送人

		// 邮件详情webview加载数据
		webView.loadDataWithBaseURL(null, contentEmail.getContent(),
				"text/html", "utf-8", null);
		if (contentEmail.getIsHaveFile()) {
			// 如果含有附件，显示listview
			attachListView.setVisibility(View.VISIBLE);
			listAdapter = new DetailListAdapter(EmailDetailsAct.this, files);
			// listview设置适配器
			attachListView.setAdapter(listAdapter);
			setListViewHeight(attachListView);

		}

	}

	private void initView() {
		// backImageView = (ImageView) findViewById(R.id.emaildetail_back);
		hideTextView = (TextView) findViewById(R.id.textbut_hide);
		detailTextView = (TextView) findViewById(R.id.textbut);
		hideRelativeLayout = (RelativeLayout) findViewById(R.id.email_detail);
		simplerRelativeLayout = (RelativeLayout) findViewById(R.id.email_simple);
		// backImageView.setOnClickListener(this);
		hideTextView.setOnClickListener(this);
		detailTextView.setOnClickListener(this);
		chaosongrtenTextView = (TextView) findViewById(R.id.chasongren_name);
		misongrenTextView = (TextView) findViewById(R.id.misongren_name);
		emailthemeText = (TextView) findViewById(R.id.email_detail_theme);
		emailAdresserText = (TextView) findViewById(R.id.email_detail_addresser);
		emailAdresserText1 = (TextView) findViewById(R.id.email_detail_addresser1);
		emailAdresserAdressText = (TextView) findViewById(R.id.email_detail_addresser1_addrerss);
		emailshoujianrenText = (TextView) findViewById(R.id.shoujianren_email);
		emailTimeText = (TextView) findViewById(R.id.email_time);
		emaishoujianrenName = (TextView) findViewById(R.id.shoujianren_name);

		replyLayout = (LinearLayout) findViewById(R.id.emailreply);
		copytoLayout = (LinearLayout) findViewById(R.id.emailcopyto);
		deleteLayout = (LinearLayout) findViewById(R.id.emaildelete);
		replyLayout.setOnClickListener(this);
		copytoLayout.setOnClickListener(this);
		deleteLayout.setOnClickListener(this);

		attachListView = (ListView) findViewById(R.id.detail_listview);

		emailContentTextView = (TextView) findViewById(R.id.emaildetail_content);
		webView = (WebView) findViewById(R.id.email_webview);

		RelativeLayout include = (RelativeLayout) findViewById(R.id.include);
		include.setBackgroundResource(R.color.red_ios);
		LinearLayout leftbacklayout = (LinearLayout) findViewById(R.id.leftbacklayout);
		leftbacklayout.setVisibility(View.VISIBLE);
		TextView title = (TextView) findViewById(R.id.fragmenttitle);
		leftbacklayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		title.setText("邮件详情");
		title.setTextColor(Color.WHITE);

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.textbut_hide) {
			simplerRelativeLayout.setVisibility(View.VISIBLE);
			hideRelativeLayout.setVisibility(View.GONE);
		}else if (id == R.id.textbut) {
			simplerRelativeLayout.setVisibility(View.GONE);
			hideRelativeLayout.setVisibility(View.VISIBLE);
		}else if (id == R.id.emailreply) {// 回复  回复和转发的接口都为重新发送邮件的接口，需要附带上原来邮件的内容、附件。这个因为时间原因等闫回来了整吧。
			skipActivity("reply");
			//Toast.makeText(EmailDetailsAct.this, "正在开发中...", Toast.LENGTH_SHORT)
			//.show();
		}else if (id == R.id.emailcopyto) {// 转发
			skipActivity("copyto");
			//	Toast.makeText(EmailDetailsAct.this, "正在开发中...", Toast.LENGTH_SHORT).show();
		}else if (id == R.id.emaildelete) {// 删除按钮
			Intent intent = getIntent();
			intent.putExtra("deleteTag", true);
			EmailDetailsAct.this.setResult(2, intent);
			this.finish();
		}
	}

	/**
	 * 点击 回复 转发 跳转到 发送邮件界面
	 *
	 */
	private void skipActivity(String tag) {
		String sender = dbEmail.getFrom();
		// 如果邮件zhiti不为空，才可以跳转
		if (sender != null) {

			Intent intent = new Intent(EmailDetailsAct.this,
					EmailWriteAct.class);

			// 转发的时候 internt传递数据不传递附件缩略图
			ArrayList<AttachFile> transferFiles = new ArrayList<AttachFile>();

			if (files != null) {
				for (int i = 0; i < files.size(); i++) {
					// 移除文件中的图片
					files.get(i).setAttachImage(null);
					transferFiles.add(files.get(i));
				}
			}

			Email passEmail = new Email();
			passEmail.setMessageID(emailData.getMessageID());
			passEmail.setTo(dbEmail.getTo());
			passEmail.setFrom(dbEmail.getFrom());
			passEmail.setContent(dbEmail.getContent());
			passEmail.setSentdata(emailData.getSentdata());
			passEmail.setIsHaveFile(emailData.getIsHaveFile());
			passEmail.setSubject(dbEmail.getSubject());
			emailData.setContent(dbEmail.getContent());
			if (tag.equals("reply")) {
				intent.putExtra("reply", passEmail);
			} else {
				intent.putExtra("copyto", passEmail);
			}
			intent.putExtra("files", (Serializable) transferFiles);
			intent.putExtra("emailtype", emailType);
			startActivity(intent);
		} else {
			Toast.makeText(EmailDetailsAct.this, "加载数据失败，暂时无法操作！",
					Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 重新计算ListView的高度，解决ScrollView和ListView两个View都有滚动的效果，在嵌套使用时起冲突的问题
	 *
	 * @param listView
	 */
	public void setListViewHeight(ListView listView) {

		// 获取ListView对应的Adapter

		DetailListAdapter listAdapter = (DetailListAdapter) listView
				.getAdapter();

		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	/**
	 * 加在收件箱详情数据
	 */
	private void loadHeadOfficeDetailByNet() {
		Log.i(TAG, "加在收件箱详情数据");
		new AsyncTask<Void, Void, JResponseObject>() {

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				// 加载dialog显示
				LoadingDataUtilBlack.show(EmailDetailsAct.this);
			}

			@SuppressWarnings("unused")
			@Override
			protected JResponseObject doInBackground(Void... params) {
				// 创建PO

				JParamObject PO = JParamObject.Create();
				JResponseObject RO = null;

				String usereId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
				String password = EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD);
				// 普光tokenid
				String tokenId = (String) EnvironmentVariable.getProperty(
						"EmailTokenId", "");
				// 总部tokenid
				String DPtokenId = (String) EnvironmentVariable.getProperty(
						"DPEmailTokenId", "");
				System.out.println(emailData.getMessageID());
				if (emailType.equals("DPEMAIL")) {//总部邮箱详情
				PO.SetValueByParamName("WB_SYS_KEY", "DPEMAIL");
				PO.SetValueByParamName("DPEMAIL_systemmethod", "EmailDetails");
				PO.SetValueByParamName("DPEMAIL_params_ItemID",
						emailData.getMessageID());
				PO.SetValueByParamName("DPEMAIL_params_tokenIDFromMoblie",
						DPtokenId);
				}else if (emailType.equals("EMAIL")) {//普光邮箱详情
					PO.SetValueByParamName("WB_SYS_KEY", "EMAIL");
					PO.SetValueByParamName("EMAIL_systemmethod", "EmailDetails");
					PO.SetValueByParamName("EMAIL_params_ItemID",
							emailData.getMessageID());
					PO.SetValueByParamName("EMAIL_params_tokenIDFromMoblie",
							tokenId);
				}

				try {
					// 连接服务器
					RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
					System.out.println("..........");
				} catch (Exception e) {
					e.printStackTrace();
				}

				return RO;
			}

			@SuppressWarnings({ "unused", "unchecked" })
			@Override
			protected void onPostExecute(JResponseObject result) {
				super.onPostExecute(result);

				if (result != null) {

					Map<String, Object> map = result.getResponseMap();
					EFDataSet emailEFDataSet = (EFDataSet) map.get(emailType);
					if (emailEFDataSet != null) {
						List<EFRowSet> list = emailEFDataSet.getRowSetArray();

						for (EFRowSet oneInfoRowSet : list) {
							String id = emailData.getMessageID();
							String receivers = AbStrUtil
									.getEmailAddress(oneInfoRowSet.getString(
											"Receivers", ""));
							//对于普光邮箱 收件人可能包含字符 <b>  去掉这些字符
							if (receivers.contains("<b>")) {
								receivers = receivers.replace("<b>", "");
								if (receivers.contains("</b>")) {
									receivers = receivers.replace("</b>", "");
								}
							}
							String chaoSong = AbStrUtil
									.getEmailAddress(oneInfoRowSet.getString(
											"ChaoSong", ""));
							String miSong = AbStrUtil
									.getEmailAddress(oneInfoRowSet.getString(
											"MiSong", ""));
							String subject = oneInfoRowSet.getString("Subject",
									"");
							String content = oneInfoRowSet.getString("Content",
									"");
							String sender = AbStrUtil
									.getEmailAddress(oneInfoRowSet.getString(
											"Sender", ""));
							String sendDate = oneInfoRowSet.getString(
									"DeliveredDate", "");

							contentEmail.setMessageID(id);
							contentEmail.setTo(receivers);
							contentEmail.setFrom(sender);
							contentEmail.setContent(content);
							contentEmail.setCopyTo(chaoSong);
							contentEmail.setSentdata(sendDate);
							contentEmail.setSecretTo(miSong);
							contentEmail.setSubject(subject);
							contentEmail.setIsHaveFile(emailData
									.getIsHaveFile());

							dbEmail = contentEmail;
							if (boxType.equals("inbox")) {
								inboxEmailsDAO.updateEmail(contentEmail);
							}else if (boxType.equals("outbox")) {
								outboxEmailsDAO.updateEmail(contentEmail);
							}


							// 如果有附件
							if (emailData.getIsHaveFile()) {
								files = new ArrayList<AttachFile>();
								//{url=http://10.80.1.199/download_mobile.aspx, ContentType=,
								//_Self_RowSet=, Attachementname=普光分公司内部邮件系统升级——用户手册.docx}
								EFDataSet attachEFDataSet = oneInfoRowSet
										.getChildDataSet();
								if (attachEFDataSet != null) {

								List<EFRowSet> attachList = attachEFDataSet
										.getRowSetArray();
								for (int j = 0; j < attachEFDataSet
										.getRowCount(); j++) {
									EFRowSet attachRowSet = attachList.get(j);

									String Attachementname = attachRowSet
											.getString("Attachementname", "");
									String url = attachRowSet.getString("url",
											"");
									if ("EMAIL".equals(emailType)) {
										//url = url +"?mailid="+emailData.getMessageID()+"&filename="+Attachementname;


									}
									String type = attachRowSet.getString(
											"ContentType", "");

									AttachFile attachFile = new AttachFile();
									attachFile.setAttachName(Attachementname);
									attachFile.setAttachPath(url);
									Bitmap bmp = null;
									if ("DPEMAIL".equals(emailType)) {
										 bmp = FileUtil.getImageFrompath(
												EmailDetailsAct.this, url);
									}else {
										 bmp = FileUtil.getImageFrompath(
												EmailDetailsAct.this, Attachementname);
									}

									Drawable drawable = new BitmapDrawable(bmp);
									attachFile.setAttachImage(drawable);
									attachFile.setAttachSize("");//设置文件大小，随便设置的，为空后面会报错
									attachFile.setId(emailData.getMessageID());
									attachFile.setEmailType(emailType);
									attachFile.setBoxType(boxType);
									files.add(attachFile);
								}
								attachmentEmailsDAO.saveSetFiles(files);
							}
							}

						}


						initData(contentEmail);

					}
				} else {
					Toast.makeText(EmailDetailsAct.this, ResStringUtil.getString(R.string.common_text_no_data),
							Toast.LENGTH_SHORT).show();
				}

				LoadingDataUtilBlack.dismiss();

			}

		}.execute();

	}
}
